package org.jeecg.modules.middle.auditCenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.LimitSubmit;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.api.IManageBaseAPI;
import org.jeecg.modules.manage.entity.CaishuiTaskSettle;
import org.jeecg.modules.manage.entity.CaishuiTaskSettleItem;
import org.jeecg.modules.manage.vo.CaishuiTaskSettlePage;
import org.jeecg.modules.middle.auditCenter.service.ICaishuiTaskSettleItemService;
import org.jeecg.modules.middle.auditCenter.service.ICaishuiTaskSettleService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 任务结算审核[中台]
 * @Author: yfkj
 * @Date:   2023-02-20
 * @Version: V1.0
 */
@Api(tags="任务结算审核[中台]")
@RestController
@RequestMapping("/auditCenter/caishuiTaskSettle")
@Slf4j
public class CaishuiTaskSettleController {

	@Autowired
	private ICaishuiTaskSettleService caishuiTaskSettleService;
	@Autowired
	private ICaishuiTaskSettleItemService caishuiTaskSettleItemService;
	@Autowired
	private RedisUtil redisUtil;
	//注入feign客户端
	@Resource
	private IManageBaseAPI iManageBaseAPI;

	/**
	 * 分页列表查询
	 *
	 * @param caishuiTaskSettle
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="任务结算审核[中台]-分页列表查询", notes="任务结算审核[中台]-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CaishuiTaskSettle>> queryPageList(CaishuiTaskSettle caishuiTaskSettle,
														  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														  HttpServletRequest req) {
		QueryWrapper<CaishuiTaskSettle> queryWrapper = QueryGenerator.initQueryWrapper(caishuiTaskSettle, req.getParameterMap());
		Page<CaishuiTaskSettle> page = new Page<CaishuiTaskSettle>(pageNo, pageSize);
		IPage<CaishuiTaskSettle> pageList = caishuiTaskSettleService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 分页列表查询任务结算详情
	 *
	 * @param caishuiTaskSettleItem
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="任务结算审核[中台]-分页列表查询任务结算详情", notes="任务结算审核[中台]-分页列表查询任务结算详情")
	@GetMapping(value = "/itemList")
	public Result<IPage<CaishuiTaskSettleItem>> queryPageitemList(CaishuiTaskSettleItem caishuiTaskSettleItem,
															  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															  HttpServletRequest req) {
		QueryWrapper<CaishuiTaskSettleItem> queryWrapper = QueryGenerator.initQueryWrapper(caishuiTaskSettleItem, req.getParameterMap());
		Page<CaishuiTaskSettleItem> page = new Page<CaishuiTaskSettleItem>(pageNo, pageSize);
		IPage<CaishuiTaskSettleItem> pageList = caishuiTaskSettleItemService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 审批操作
	 * @param id
	 * @param status
	 * @return
	 */
	@AutoLog(value = "任务结算审核[中台]-审批操作", terminal = 1)
	@ApiOperation(value="任务结算审核[中台]-审批操作", notes="任务结算审核[中台]-审批操作")
	@GetMapping(value = "/status")
	@LimitSubmit(key = "middle:taskSettle:status:%tId", spelKey = "#id")
	public Result<?> status(@RequestParam(name="id",required=true) String id,
							@RequestParam(name="captcha",required=true) String captcha,
							@RequestParam(name="status",required=true) int status) {
		//从缓存中获取手机验证码
		Object code = redisUtil.get(CommonConstant.PHONE_REDIS_KEY_PRE + TokenUtils.getLoginUser().getUsername());
		if(oConvertUtils.isEmpty(code)){
			return Result.error("短信验证码已失效！");
		}else if (!captcha.equals(code)) {
			return Result.error("短信验证码错误！");
		}

		//任务结算信息
		CaishuiTaskSettle caishuiTaskSettle = caishuiTaskSettleService.getById(id);
		if (oConvertUtils.isEmpty(caishuiTaskSettle)) {
			return Result.error("任务结算信息错误！");
		}else if(caishuiTaskSettle.getStatus()!=1 && caishuiTaskSettle.getExtendStatus()!=0){
			return Result.error("任务结算信息错误！");
		}

		//判断是否还存在发放中的批次任务
		long count = caishuiTaskSettleService.count(QueryGenerator.initQueryWrapper(new CaishuiTaskSettle(),null)
				.lambda().eq(CaishuiTaskSettle::getCompanyId,caishuiTaskSettle.getCompanyId())
				.eq(CaishuiTaskSettle::getBusinessId,caishuiTaskSettle.getBusinessId()).eq(CaishuiTaskSettle::getExtendStatus,1));
		if(count > 0){
			return Result.error("请耐心等待上一个批次发放完成之后再下发！");
		}

		if(status==3){//驳回
			caishuiTaskSettle.setStatus(3);
			caishuiTaskSettle.setExtendStatus(3);
			caishuiTaskSettle.setCheckTime(new Date());
			caishuiTaskSettleService.updateById(caishuiTaskSettle);
			return Result.OK("审核成功!");
		}else if(status==2){//通过
			//feign调用发放接口
			return iManageBaseAPI.doIssuedSalary(caishuiTaskSettle);
		}else {
			return Result.error("操作失败！");
		}
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="任务结算审核[中台]-通过主表ID查询", notes="任务结算审核[中台]-通过主表ID查询")
	@GetMapping(value = "/queryCaishuiTaskSettleItemByMainId")
	public Result<IPage<CaishuiTaskSettleItem>> queryCaishuiTaskSettleItemListByMainId(@RequestParam(name="id",required=true) String id) {
		List<CaishuiTaskSettleItem> caishuiTaskSettleItemList = caishuiTaskSettleItemService.selectByMainId(id);
		IPage <CaishuiTaskSettleItem> page = new Page<>();
		page.setRecords(caishuiTaskSettleItemList);
		page.setTotal(caishuiTaskSettleItemList.size());
		return Result.OK(page);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param caishuiTaskSettle
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CaishuiTaskSettle caishuiTaskSettle) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<CaishuiTaskSettle> queryWrapper = QueryGenerator.initQueryWrapper(caishuiTaskSettle, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
           List<String> selectionList = Arrays.asList(selections.split(","));
           queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<CaishuiTaskSettle>  caishuiTaskSettleList = caishuiTaskSettleService.list(queryWrapper);

      // Step.3 组装pageList
      List<CaishuiTaskSettlePage> pageList = new ArrayList<CaishuiTaskSettlePage>();
      for (CaishuiTaskSettle main : caishuiTaskSettleList) {
          CaishuiTaskSettlePage vo = new CaishuiTaskSettlePage();
          BeanUtils.copyProperties(main, vo);
          List<CaishuiTaskSettleItem> caishuiTaskSettleItemList = caishuiTaskSettleItemService.selectByMainId(main.getId());
          vo.setCaishuiTaskSettleItemList(caishuiTaskSettleItemList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "任务结算审核[中台]列表");
      mv.addObject(NormalExcelConstants.CLASS, CaishuiTaskSettlePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("任务结算审核[中台]数据", "导出人："+sysUser.getRealname(), "任务结算审核[中台]"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

}
